<template>
  <el-dialog
      :model-value="visible"
      @update:model-value="$emit('update:visible', $event)"
      title="个人信息"
      width="500px"
      :close-on-click-modal="false"
      @closed="handleDialogClosed">
    <el-form :model="userForm" label-width="80px" :rules="formRules" ref="userFormRef">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userForm.username" disabled/>
      </el-form-item>
      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="userForm.nickname" placeholder="请输入昵称"/>
      </el-form-item>
      <el-form-item label="头像">
        <div class="avatar-uploader">
          <el-avatar :src="userForm.avatar || defaultAvatar" :size="80">
            <span v-if="!userForm.avatar">{{ userForm.username?.charAt(0)?.toUpperCase() || 'U' }}</span>
          </el-avatar>

          <!-- 替换为手动上传实现 -->
          <el-button type="primary" @click="showSelectFile">
            修改头像
          </el-button>
          <input ref="fileInputRef" type="file" accept="image/*" style="display:none" @change="handleFileChange" />
        </div>

        <!-- 添加头像裁剪对话框 -->
        <el-dialog
            v-model="cropper.open"
            title="修改头像"
            width="800px"
            append-to-body
            :close-on-click-modal="false">
          <el-row>
            <el-col :xs="24" :md="12" :style="{height: '350px'}">
              <vue-cropper
                  ref="cropperRef"
                  :img="cropper.options.img"
                  :info="true"
                  :autoCrop="true"
                  :autoCropWidth="200"
                  :autoCropHeight="200"
                  :fixedBox="true"
                  @realTime="realTime"
                  v-if="cropper.open"
              />
            </el-col>
            <el-col :xs="24" :md="12" :style="{height: '350px'}">
              <div class="avatar-preview-box">
                <div class="preview-item">
                  <img :src="cropper.previews.url" :style="cropper.previews.img" />
                </div>
              </div>
            </el-col>
          </el-row>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="cropper.open = false">取消</el-button>
              <el-button type="primary" @click="uploadAvatar" :loading="cropper.uploading">
                确认
              </el-button>
            </div>
          </template>
        </el-dialog>
      </el-form-item>
      <el-form-item label="邮箱" prop="email">
        <el-input v-model="userForm.email" placeholder="请输入邮箱"/>
      </el-form-item>
      <el-form-item label="手机" prop="phone">
        <el-input v-model="userForm.phone" placeholder="请输入手机号"/>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog">取消</el-button>
        <el-button type="primary" @click="saveUserProfile" :loading="saving">
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, defineProps, defineEmits, watch } from 'vue';
import { ElMessage } from 'element-plus';
import userStore from '@/store/user';
import {updateUserProfile, uploadAvatarApi} from '@/api/user';
import { getToken } from '@/utils/auth';
// 导入VueCropper组件
import { VueCropper } from 'vue-cropper';
import 'vue-cropper/dist/index.css';

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
});

const emit = defineEmits(['update:visible', 'profile-updated']);

// 表单实例和状态
const userFormRef = ref(null);
const fileInputRef = ref(null);
const cropperRef = ref(null);
const saving = ref(false);
const defaultAvatar = ref(require('@/assets/images/profile.jpg'));

// 头像裁剪相关
const cropper = ref({
  open: false,
  options: {
    img: '',
    autoCrop: true,
    autoCropWidth: 200,
    autoCropHeight: 200,
    fixedBox: true
  },
  previews: {},
  uploading: false
});

// 用户表单数据
const userForm = ref({
  username: '',
  nickname: '',
  avatar: '',
  email: '',
  phone: ''
});

// 表单验证规则
const formRules = {
  nickname: [
    {required: true, message: '请输入昵称', trigger: 'blur'},
    {min: 2, max: 20, message: '昵称长度应为2-20个字符', trigger: 'blur'}
  ],
  email: [
    {type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur'}
  ],
  phone: [
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur'}
  ]
};

// 监听对话框可见性变化，初始化表单数据
watch(() => props.visible, (newVal) => {
  if (newVal) {
    initUserForm();
  }
});

// 初始化用户表单数据
const initUserForm = () => {
  userForm.value = {
    username: userStore.getUserName() || '',
    nickname: userStore.getNickname() || '',
    avatar: userStore.getAvatar() || '',
    email: userStore.getEmail() || '',
    phone: userStore.getPhone() || ''
  };
};

// 打开文件选择对话框
const showSelectFile = () => {
  fileInputRef.value.click();
};

// 处理文件选择变化
const handleFileChange = (e) => {
  const file = e.target.files[0];
  if (!file) return;

  // 验证文件类型和大小
  const isImage = file.type.startsWith('image/');
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('上传头像图片只能是图片格式!');
    return;
  }
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!');
    return;
  }

  // 创建文件预览URL
  const reader = new FileReader();
  reader.onload = (event) => {
    cropper.value.options.img = event.target.result;
    cropper.value.open = true;
  };
  reader.readAsDataURL(file);

  // 重置文件输入，允许选择同一文件
  e.target.value = '';
};

// 实时获取裁剪预览
const realTime = (data) => {
  cropper.value.previews = data;
};

// 上传头像
const uploadAvatar = async () => {
  cropper.value.uploading = true;

  try {
    // 获取裁剪后的blob数据
    const canvas = await cropperRef.value.getCropBlob((data) => {
      const formData = new FormData();
      formData.append('avatarfile', data, 'avatar.png');

      // 使用导入的uploadAvatar函数而不是直接使用request
      uploadAvatarApi(formData).then(res => {
        cropper.value.uploading = false;
        if (res.code === 200) {
          cropper.value.open = false;
          userForm.value.avatar =  process.env.VUE_APP_BASE_API +res.imgUrl;
          ElMessage.success('头像上传成功');
        } else {
          ElMessage.error(res.msg || '头像上传失败');
        }
      }).catch(err => {
        cropper.value.uploading = false;
        console.error('头像上传失败:', err);
        ElMessage.error('头像上传失败');
      });
    });
  } catch (error) {
    cropper.value.uploading = false;
    console.error('头像处理失败:', error);
    ElMessage.error('头像处理失败');
  }
};

// 关闭对话框
const closeDialog = () => {
  emit('update:visible', false);
};

// 对话框关闭后的回调
const handleDialogClosed = () => {
  if (userFormRef.value) {
    userFormRef.value.resetFields();
  }
};

// 保存用户信息
const saveUserProfile = async () => {
  if (!userFormRef.value) return;

  try {
    // 表单验证
    await userFormRef.value.validate();

    saving.value = true;

    // 调用API保存用户信息
    const res = await updateUserProfile({
      userName: userForm.value.username,
      nickName: userForm.value.nickname,
      avatar: userForm.value.avatar,
      email: userForm.value.email,
      phonenumber: userForm.value.phone
    });

    if (res.code === 200) {
      // 更新本地存储的用户信息
      userStore.setNickname(userForm.value.nickname);
      userStore.setAvatar( userForm.value.avatar);
      userStore.setEmail( userForm.value.email);
      userStore.setPhone( userForm.value.phone);


      // 通知父组件更新成功
      emit('profile-updated', {
        nickname: userForm.value.nickname,
        avatar: userForm.value.avatar
      });

      ElMessage.success('个人信息更新成功');
      closeDialog();
    } else {
      ElMessage.error(res.msg || '保存失败');
    }
  } catch (error) {
    console.error('保存个人信息失败:', error);
    ElMessage.error('表单验证失败或保存过程出错');
  } finally {
    saving.value = false;
  }
};
</script>

<style scoped>
.avatar-uploader {
  display: flex;
  align-items: center;
  gap: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 头像裁剪预览样式 */
.avatar-preview-box {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  height: 100%;
}

.preview-item {
  width: 200px;
  height: 200px;
  overflow: hidden;
  border: 1px solid #dcdfe6;
  border-radius: 50%;
}

:deep(.el-dialog__body) {
  padding: 20px 25px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-avatar > span) {
  line-height: 80px;
  font-size: 32px;
  font-weight: bold;
  color: #2c56a0;
}
</style>